<?php

namespace App\Http\Controllers\Auth;

use App\Events\InviteUsersRegister;
use App\Http\Proxy\TokenProxy;
use App\User;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Redis;
use Mrgoon\AliSms\AliSms;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;
    protected $proxy;
    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(TokenProxy $proxy)
    {
        $this->middleware('guest')->except('logout');
        $this->proxy = $proxy;
    }

    /**
     * @param Request $request 用户注册信息
     * @return \Illuminate\Http\JsonResponse  返回注册成功或者失败
     */
    public function register(Request $request)
    {
        if (Redis::get($request->mobile) == $request->code) {
            $data = $request->validate([
                'name' => 'required|string|max:255|unique:users',
                'mobile' => 'required|regex:/^1[34578][0-9]{9}$/|unique:users',
                'password' => 'required|string|min:6',
            ]);
            if(request('invite_code')){
                $data['is_vip'] = 1;
//                $data['vipduetime'] = Carbon::parse('+7 days')->toDateTimeString();
                $data['vipduetime'] = Carbon::now();
                $user = $this->create($data);
                $user->invite_code = request('invite_code');
//                监听邀请用户注册给邀请人赠送7天VIP
                event(new InviteUsersRegister($user));
            }else{
                //活动注册奖励VIP
                $data['is_vip'] = 1;
//                $data['vipduetime'] = Carbon::parse('+7 days')->toDateTimeString();
                $data['vipduetime'] = Carbon::now();
                $this->create($data);
            }
            return response()->json(['status' => 1, 'message' => '注册成功']);
        }else{
            return response()->json(['status' => 0, 'message' => '验证码错误']);
        }
    }


    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'mobile' => $data['mobile'],
            'password' => bcrypt($data['password']),
            'is_vip' => $data['is_vip'],
            'vipduetime' => $data['vipduetime']
        ]);
    }

    public function sendcode(Request $req)
    {
        switch (request('method'))
        {
            case 'register':
                $rule = 'required|regex:/^1[34578][0-9]{9}$/|unique:users';
                $template = 'SMS_151040148';
                break;
            case 'forgotpass':
                $rule = 'required|regex:/^1[34578][0-9]{9}$/|exists:users';
                $template = 'SMS_151040150';
                break;
            case 'tixiancode':
                $rule = 'required|regex:/^1[34578][0-9]{9}$/|exists:users';
                $template = 'SMS_151075126';
                break;
            case 'bangding':
                $rule = 'required|regex:/^1[34578][0-9]{9}$/';
                $template = 'SMS_153420154';
                break;
            default:
                return response()->json(['message' => '参数错误', 'status' => 0]);
        }
        $req->validate([
            'mobile' => $rule,
        ]);
        $code = rand(100000, 999999);
        Redis::setex($req->mobile,300,$code);
        $aliSms = new AliSms();
        $res = $aliSms->sendSms($req->mobile, $template, ['code' => $code]);
        if ($res->Code == 'OK') {
            $data = [
                'message' => '发送成功',
                'status' => 1
            ];
            if(request('method') == 'bangding' ){
                if(User::where('mobile',$req->mobile)->first()){
                    $data['registed'] = 1;
                }else{
                    $data['registed'] = 0;
                }
            }
            return response()->json($data);
        }
        return response()->json(['message' => '发送失败', 'status' => 0]);
    }
    //第三方登录注册
    public function threeregister(Request $request)
    {
        if (Redis::get($request->mobile) == $request->code) {
            $data = $request->validate([
                'name' => 'sometimes|required|string|max:255|unique:users',
                'avatar' => 'required',
                'mobile' => 'required|regex:/^1[34578][0-9]{9}$/|',
                'type' => 'required',
                'openid' => 'required',
                'password' => 'sometimes|required|string|min:6',
            ]);
            if($request->registed == 1){
               $userInfo = User::where('mobile',$request->mobile)->first();
               $user = [
                   $data['type'].'name' => $data['name'],
                   $data['type'].'openid' => $data['openid'],
               ];
               if($userInfo->avatar == ''){
                   $user['avatar'] = $data['avatar'];
               }
               $userInfo->update($user);
            }else{
                $user = [
                    $data['type'].'name' => $data['name'],
                    $data['type'].'openid' => $data['openid'],
                    'avatar' => $data['avatar'],
                    'password' => bcrypt($data['password']),
                    'name' => $data['name'],
                    'mobile' => $data['mobile'],
                ];
                $userInfo = User::create($user);
            }
            return $this->proxy->proxy('password', [
                'username' => $userInfo->mobile,
                'password' => $userInfo->password,
                'scope'    => '',
            ]);
        }else{
            return response()->json(['status' => 0, 'message' => '验证码错误']);
        }
    }
}
